
const subscribeOnces = {}; //保存订阅对象,避免重复订阅-单次
const subscribes = {}; //保存订阅对象,避免重复订阅-多次

export default {
  FOLLOW_FAST_START:"follow_fast_start", // 跟单模块--一键跟单操作消息
  EXECUTE_UPDATE:"execute_update", // 策略执行模块--策略执行状态发送改变
  VIP_BUY_OK:"vip_buy_ok", // 会员购买成功
  PHONE_BUY_OK:"phone_buy_ok", // 电话条数购买成功
  

  /** 发送消息
   * 
   * @param {String} channel 消息频道
   * @param {Any} data 数据
   */
  send(channel, data = true){
    const receiver = new BroadcastChannel(channel);
    try {
      receiver.postMessage(data);
    } catch (error) {
      receiver.close();
    }finally{
      receiver.close();
    }
  },

  /** 订阅消息,持续订阅
   * 
   * @param {String} key 重复订阅处理关键字
   * @param {String} channel 消息频道
   * @param {Function} handler 消息处理者
   */
  subscribe(key, channel, handler){

    //取消重复订阅的消息
    var receiver = subscribes[key];
    if (receiver) {
      receiver.close();
      delete subscribes[key];
    }

    receiver = new BroadcastChannel(channel);
    subscribeOnces[key] = receiver;
    receiver.onmessage = function(event){
      try {
        handler&&handler(event.data);
      } catch (error) {
      }
    };
    return receiver;
  },

  /** 订阅消息一次消息
   * 
   * @param {String} channel 消息频道
   * @param {Callback} handler 消息处理者
   */
  subscribeOnce(channel, handler){

    //取消重复订阅的消息
    var receiver = subscribeOnces[channel];
    if (receiver) {
      receiver.close();
      delete subscribeOnces[channel];
    }

    //订阅消息
    receiver = new BroadcastChannel(channel);
    subscribeOnces[channel] = receiver;
    receiver.onmessage = function(event){
      try {
        handler&&handler(event.data);
      } catch (error) {
        receiver.close();
      }finally{
        receiver.close();
      }
    };
    return receiver;
  }
}